package cn.yll.web.controller;

import cn.yll.api.order.request.CashOrderRequest;
import cn.yll.api.order.request.OrderLineRequest;
import cn.yll.api.order.request.OrderRequest;
import cn.yll.api.order.response.OrderResponse;
import cn.yll.api.order.service.RemoteOrderFeinService;
import cn.yll.api.user.request.UserCashRequest;
import cn.yll.api.user.service.RemoteUserFeignService;
import cn.yll.api.conf.UserAuthorize;
import cn.yll.api.util.JwtUserUtil;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import cn.yll.common.module.RestModel;
import cn.yll.api.util.RestUtil;
import cn.yll.common.utils.JwtTokenUtil;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * 订单控制器
 *
 * @author yangll
 */
@Slf4j
@UserAuthorize
@RestController("order")
@Api(tags = "订单控制器")
public class OrderController extends BaseController {

    @Autowired
    private RemoteOrderFeinService remoteOrderFeinService;
    @Autowired
    private RemoteUserFeignService remoteUserFeignService;

    /**
     * seata AT模式的分布式事务实现
     */
    @PostMapping("create")
    @GlobalTransactional(rollbackFor = Exception.class)
    @ApiOperation(value = "创建订单", notes = "所有参数必填，需要登录态，返回订单ID")
    public RestModel<Long> createOrder(@RequestBody List<OrderLineRequest> lines) {
        Long userId = JwtUserUtil.getLoginUserId();
        if (Objects.isNull(userId)) {
            return RestUtil.error(BsErrEnum.NEED_LOGIN);
        }
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.setUserId(userId);
        orderRequest.setLines(lines);

        //第1步，扣减商品库存，并创建商品订单和购买记录
        RestModel<OrderResponse> restModel = remoteOrderFeinService.createOrder(orderRequest);
        if (!RestUtil.isSuccess(restModel) || Objects.isNull(restModel.getData())) {
            throw new BsException(BsErrEnum.REQUEST_ERROR, Objects.nonNull(restModel) ? restModel.getMessage() : null);
        }
        OrderResponse order = restModel.getData();
        UserCashRequest request = new UserCashRequest();
        request.setUserId(userId);
        request.setCash(order.getTotalCost());
        request.setPay(true);
        //第2步 扣减用户账户余额
        RestModel<Boolean> cashRestModel = remoteUserFeignService.addCash(request);
        if (!RestUtil.isSuccess(cashRestModel) || !cashRestModel.getData()) {
            throw new BsException(BsErrEnum.REQUEST_ERROR, Objects.nonNull(cashRestModel) ? cashRestModel.getMessage() : null);
        }

        CashOrderRequest cashOrderRequest = new CashOrderRequest();
        cashOrderRequest.setOrderId(order.getId());
        cashOrderRequest.setUserId(userId);
        cashOrderRequest.setTotalCost(order.getTotalCost());
        //第3步 完成订单，修改订单支付状态
        RestModel<?> cashOrderRes = remoteOrderFeinService.cashOrder(cashOrderRequest);
        if (RestUtil.isSuccess(cashOrderRes)) {
            return RestUtil.sucess(order.getId());
        } else {
            throw new BsException(BsErrEnum.REQUEST_ERROR, cashOrderRes.getMessage());
        }
    }
}
